import Vue from "vue";
import VueRouter from "vue-router";
import Home from "@/views/HomeView";
import Orders from "@/views/OrdersView";
import Cart from "@/views/CartView";
import RegisterView from "@/views/RegisterView";
import LoginView from "@/views/LoginView";
import FavoritesView from "@/views/FavoritesView";
import ReviewsView from "@/views/ReviewsView";
import CheckOut from "@/views/CheckOut";
import store from '../stores';

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/home"
  },
  {
    path: "/home",
    component: Home
  },
  {
    path: "/orders",
    component: Orders,
    meta: { requiresAuth: true }
  },
  {
    path: "/cart",
    component: Cart,
    meta: { requiresAuth: true }
  },
  {
    path: "/register",
    component: RegisterView
  },
  {
    path: "/login",
    component: LoginView
  },
  {
    path: "/favorites",
    component: FavoritesView,
    meta: { requiresAuth: true }
  },
  {
    path: "/reviews",
    component: ReviewsView,
    meta: { requiresAuth: true }
  },
  {
    path: "/checkout",
    component: CheckOut,
    meta: { requiresAuth: true }
  },
  {
    path: '/book/:id',
    name: 'BookDetail',
    component: () => import('../views/BookDetail.vue'),
    props: true
  }
];

const router = new VueRouter({
  routes: routes
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!store.getters.isLoggedIn) {
      next({
        path: '/login',
        query: { redirect: to.fullPath, message: '请先登录' }
      });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;